/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Boundary;

import Entity.Employee;
import Entity.MedicalRecord;
import Entity.Owner;
import Services.EmployeeService;
import Services.OwnerService;
import Services.PetService;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;

/**
 *
 * @author Grace
 */
public class LoginGUI extends javax.swing.JFrame {

    /**
     * Creates new form LoguinGUI
     */
    public LoginGUI() {
        initComponents();
        this.setLocationRelativeTo(null);//centrar ventana
        this.setResizable(false);//la ventana no puede cambiar de tamaño


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldUser = new javax.swing.JTextField();
        LoginButton = new javax.swing.JButton();
        ExitButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jPasswordFieldPassword = new javax.swing.JPasswordField();
        jLabel5 = new javax.swing.JLabel();

        jLabel2.setText("Please login to begin");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("HPVAS");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Welcome to HPVAS!");

        jLabel3.setText("User name:");

        jLabel4.setText("Password:");

        jTextFieldUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUserActionPerformed(evt);
            }
        });

        LoginButton.setText("Login");
        LoginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginButtonActionPerformed(evt);
            }
        });

        ExitButton.setText("Exit");
        ExitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitButtonActionPerformed(evt);
            }
        });

        jPasswordFieldPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldPasswordActionPerformed(evt);
            }
        });

        jLabel5.setText("Healthy Pets Veterinarian Association");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jTextFieldUser)
                                .addComponent(jPasswordFieldPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)))
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(ExitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jPasswordFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LoginButton)
                    .addComponent(ExitButton))
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUserActionPerformed
        jPasswordFieldPassword.requestFocus();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldUserActionPerformed

    private void jPasswordFieldPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldPasswordActionPerformed
        LoginButton.doClick();
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordFieldPasswordActionPerformed

    private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitButtonActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_ExitButtonActionPerformed

    private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
        
        if (auth(jTextFieldUser.getText(), String.valueOf(jPasswordFieldPassword.getPassword()))) {
            //JOptionPane.showMessageDialog(rootPane, "Funciona!", "BIen!", JOptionPane.INFORMATION_MESSAGE);
            this.setVisible(false);
            MenuPrincipal mp = new MenuPrincipal();
            mp.setVisible(true);
            mp.setLocationRelativeTo(null);
        } else {
            JOptionPane.showMessageDialog(rootPane, "Username or password incorrect", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_LoginButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ExitButton;
    private javax.swing.JButton LoginButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPasswordField jPasswordFieldPassword;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldUser;
    // End of variables declaration//GEN-END:variables

    private boolean initowner(int ssn,long id, String name, String lastName, String bPlace){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HPVAS-2013-1-APU");
        OwnerService eJC = new OwnerService(emf);
        
        Owner test = new Owner();
        test.setSSN(453545456);
        test.setId(001L);        
        test.setName("Virginia");
        test.setLastName("Roseberry");
        test.setBirthPlace("Bogota");
        eJC.create(test);
        
        Owner test1 = new Owner();
        test1.setSSN(453547568);
        test1.setId(002L);        
        test1.setName("John");
        test1.setLastName("Snow");
        test1.setBirthPlace("Bogota");
        eJC.create(test1);
        
        Owner test2 = new Owner();
        test2.setSSN(453129458);
        test2.setId(003L);        
        test2.setName("Mike");
        test2.setLastName("Clarke");
        test2.setBirthPlace("Bogota");
        eJC.create(test2);
        
System.out.println("crea los owners de prueba");

        Owner OwnerporAutentificar = new Owner();
        OwnerporAutentificar.setSSN(ssn);
        OwnerporAutentificar.setId(id);                
        OwnerporAutentificar.setName(name);
        OwnerporAutentificar.setLastName(lastName);
        test2.setBirthPlace(bPlace);

        System.out.println("crea el owner por autentificar");

        List<Owner> owners = eJC.findOwnerEntities();

        System.out.println("tamaño del arreglo: " + owners.size());

        System.out.println("recupera la lista de owners");
        return false;
        
    }

    
    
    
    private boolean initpet (Long id, String name,String species,int age, float weight,String picture, Owner owner, MedicalRecord medicalrecord){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HPVAS-2013-1-APU");
        PetService eJC = new PetService(emf);
       
                
        
        return false;
    
    }
    
    private boolean auth(String username, String password) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HPVAS-2013-1-APU");
        EmployeeService eJC = new EmployeeService(emf);

        Employee prueba = new Employee();
        prueba.setPassword("1");
        prueba.setUsername("1");
        eJC.create(prueba);

        Employee prueba2 = new Employee();
        prueba.setPassword("2");
        prueba.setUsername("2");
        eJC.create(prueba2);

        Employee prueba3 = new Employee();
        prueba.setPassword("3");
        prueba.setUsername("3");
        eJC.create(prueba3);


        System.out.println("crea los usuarios de prueba");

        Employee usuarioporAutentificar = new Employee();
        usuarioporAutentificar.setUsername(username);
        usuarioporAutentificar.setPassword(password);

        System.out.println("crea el usuario por autentificar");

        List<Employee> employees = eJC.findEmployeeEntities();

        System.out.println("tamaño del arreglo: " + employees.size());

        System.out.println("recupera la lista de empleados");

        Iterator itr = employees.iterator();
        while (itr.hasNext()) {
            System.out.println("entra al while");
            if ((usuarioporAutentificar.getUsername().equals(employees.iterator().next().getUsername()))
                    && (usuarioporAutentificar.getPassword().equals(employees.iterator().next().getPassword()))) {
                System.out.println("buscando...\n");
                return true;
            } else {
                return false;
            }
        }return false;
    }
}